package com.heima.news.mq.send;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.heima.news.config.RabbitMQConfig;
import com.heima.news.domain.News;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class NewsMessageSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Async
    public void sendNewsInsertMessage(News news) {
        String json = toJson(news);
        rabbitTemplate.convertAndSend(RabbitMQConfig.NEWS_EXCHANGE, RabbitMQConfig.NEWS_INSERT_KEY, json);
    }

    @Async
    public void sendNewsUpdateMessage(News news) {
        String json = toJson(news);
        rabbitTemplate.convertAndSend(RabbitMQConfig.NEWS_EXCHANGE, RabbitMQConfig.NEWS_UPDATE_KEY, json);
    }

    @Async
    public void sendNewsDeleteMessage(News news) {
        String json = toJson(news);
        rabbitTemplate.convertAndSend(RabbitMQConfig.NEWS_EXCHANGE, RabbitMQConfig.NEWS_DELETE_KEY, json);
    }

    private String toJson(News news) {
        return JSON.toJSONString(news, SerializerFeature.WriteDateUseDateFormat);
    }
}
